package finelProject.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;

import finelProject.MyAppConstants;
import finelProject.model.Messages;

/**
 * Servlet implementation class FollowUser
 */
public class FollowUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private boolean followAlreadyExists(SQLException e) {
        boolean exists;
        if(e.getSQLState().equals("23505")) {
            exists = true;
        } else {
            exists = false;
        }
        return exists;
    }
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FollowUser() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			Context context = new InitialContext();
    		BasicDataSource ds = (BasicDataSource)context.lookup(MyAppConstants.DB_DATASOURCE);
    		Connection conn = ds.getConnection();
			String uri = request.getRequestURI();
		
			//get the names of the follower and the followe.
			String followername = uri.substring(uri.indexOf(MyAppConstants.INSERT) + MyAppConstants.FOLLOW.length() + 1,uri.lastIndexOf(MyAppConstants.SEPARATOR));
			String followename = uri.substring(uri.lastIndexOf(MyAppConstants.SEPARATOR)+1);
			followername = followername.replaceAll("\\%20", " ");
			followename = followename.replaceAll("\\%20", " ");
			
			//insert the name into the FOLLOW table in the DB
			PreparedStatement stmt;
			
			try{
		
			stmt = conn.prepareStatement(MyAppConstants.INSERT_INTO_FOLLOW);
			stmt.setString(1, followername);
			stmt.setString(2, followename);
			stmt.executeQuery();
			
			} catch (SQLException e) {

			}
			conn.close();
		}
		catch(SQLException | NamingException e){
			getServletContext().log("Error while closing connection", e);
    		response.sendError(500);//internal server error
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Collection<Messages> MessagesResult = new ArrayList<Messages>(); 
		try{
			Context context = new InitialContext();
    		BasicDataSource ds = (BasicDataSource)context.lookup(MyAppConstants.DB_DATASOURCE);
    		Connection conn = ds.getConnection();
    		PrintWriter out = response.getWriter();
			
		
			//get the names of the follower and the followe.
			String followername = (String) request.getSession().getAttribute("Username");
			String followename  = request.getParameter("followe");

			
			//insert the name into the FOLLOW table in the DB
			PreparedStatement stmt = null;
			boolean created = false;
			boolean toContinue = true;
			try{
				stmt = conn.prepareStatement(MyAppConstants.INSERT_INTO_FOLLOW);
				stmt.setString(1, followername);
				stmt.setString(2, followename);
				stmt.executeUpdate();
			
			} catch (SQLException e) {
				
				created = followAlreadyExists(e);
    			if (!created){
    				throw e;//re-throw the exception so it will be caught in the
    				//external try..catch and recorded as error in the log
    			}else{
    				out.print("alredyExist");
    				toContinue = false;
    			}
			}
			if(toContinue){
				try{
					stmt = conn.prepareStatement(MyAppConstants.GET_MESSAGES_BY_AOTUR_NAME);
					stmt.setString(1, followename);
					ResultSet rs = stmt.executeQuery();
					while (rs.next()){
						MessagesResult.add(new Messages(rs.getString(2),rs.getInt(3),rs.getTimestamp(4),rs.getString(5),rs.getString(1),(rs.getInt(7)+1),rs.getInt(6),(Math.log(2+ (rs.getInt(7)+1)) * Math.log(2+rs.getInt(3))),rs.getString(9)));
					}
			
				} catch (SQLException e) {
					getServletContext().log("Error while INSERT to FOLLOW", e);
					response.sendError(500);//internal server error
				}
			
				try{
					for(Messages message : MessagesResult){
					
						stmt = conn.prepareStatement(MyAppConstants.UPDATE_AUTOR_FOLLOERS_NUMBER);
						stmt.setInt(1, message.getAutorNumberOfFollowers());
						stmt.setDouble(2, message.getPopularity());
						stmt.setInt(3, message.getMessageId());
						stmt.executeUpdate();
					}
					out.print("Success");
				} catch (SQLException e) {
					getServletContext().log("Error while INSERT to FOLLOW", e);
					response.sendError(500);//internal server error
				}
			}
			stmt.close();
			out.close();
			conn.close();
			context.close();
		}
		catch(SQLException | NamingException e){
			getServletContext().log("Error while closing connection", e);
    		response.sendError(500);//internal server error
		}	}

}
